package com.firstgroup.dms.controller;

import com.firstgroup.dms.common.Result;
import com.firstgroup.dms.mapper.EmployeeMapper;
import com.firstgroup.dms.pojo.Employee;
import com.firstgroup.dms.pojo.Sale;
import com.firstgroup.dms.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/sale")
public class SaleController {

    @Autowired
    private SaleService saleService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @PostMapping("/add")
    public Result addSale(@RequestBody Sale sale) {
        try {
            // 计算总金额
            BigDecimal totalPrice = sale.getDetails().stream()
                    .map(detail -> detail.getPrice().multiply(new BigDecimal(detail.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            saleService.addSale(sale);
            return Result.success();
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public List<Sale> getAllSales() {
        return saleService.getAllSales();
    }

    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteSale(@PathVariable Integer id) {
        try {
            boolean success = saleService.deleteSale(id);
            return success ? Result.success(true) : Result.error("删除失败");
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/employees")
    public List<Employee> getEmployees() {
        return employeeMapper.selectAll();
    }
}
